package com.hsoft.zhxy.app.xtgl_02_01.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hsoft.zhxy.app.common.model.entity.*;
import com.hsoft.zhxy.app.xtgl_02_01.mapper.*;
import com.hsoft.zhxy.app.xtgl_02_01.model.query.JsglQuery;
import com.hsoft.zhxy.app.xtgl_02_01.model.vo.YhglVO;
import com.hsoft.zhxy.app.xtgl_02_01.model.vo.YhjsVO;
import com.hsoft.zhxy.app.xtgl_02_01.model.vo.YhjsmxVO;
import com.hsoft.zhxy.app.xtgl_02_01.service.JcqxJsService;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.hsoft.zhxy.common.base.BaseService;
import com.hsoft.zhxy.common.result.ResultBody;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * All rights Reserved, Designed By 哈尔滨工业大学软件工程股份有限公司
 *
 * @Title: 角色 Service层接口实现类
 * @Package
 * @Description:
 * @author: system
 * @date: 2020-10-26
 */
@Log4j2
@Service
public class JcqxJsServiceImpl extends BaseService implements JcqxJsService {

    @Autowired
    private JcqxJsMapper jcqxJsMapper;

    @Autowired
    private JcqxJszyMapper jszyMapper;

    @Autowired
    private JcqxYhjsMapper yhjsMapper;

    @Autowired
    private JcqxGnzyMapper gnzyMapper;

    @Autowired
    private JcqxYhjsmxMapper yhjsmxMapper;

    @Autowired
    private JcqxBmMapper bmMapper;

    /**
     * 查询单条数据
     *
     * @param jcqxJs
     * @return
     */
    public JSONObject findOne(JcqxJs jcqxJs) {
        JcqxJs rs = jcqxJsMapper.selectOne(new QueryWrapper<JcqxJs>().setEntity(jcqxJs));
        return ResultBody.setData(rs);
    }


    /**
     * 查询列表数据
     *
     * @param jcqxJs
     * @return
     */
    public JSONObject findList(JcqxJs jcqxJs) {
        List<JcqxJs> newList = new ArrayList<>();
        List<JcqxJs> list = jcqxJsMapper.selectList(new QueryWrapper<JcqxJs>().setEntity(jcqxJs).orderByAsc("pxh"));

        //查询角色所拥有的资源数量与用户数量
        for (JcqxJs js : list) {
            JcqxJszy jszy = new JcqxJszy();
            jszy.setJsid(js.getJsid());
            Integer zyCount = jszyMapper.selectCount(new QueryWrapper<JcqxJszy>().setEntity(jszy));
            js.setCountZy(zyCount);
            Integer yhCount = jcqxJsMapper.selectCountYh(js);
            js.setCountYh(yhCount);
        }

        for (JcqxJs js : list) {
            if (js.getFjsid() == null) {
                JcqxJs newJs = new JcqxJs();
                newJs.setJsid(js.getJsid());
                newJs.setJsmc(js.getJsmc());
                newJs.setJslx(js.getJslx());
                newJs.setPxh(js.getPxh());
                newJs.setCountZy(js.getCountZy());
                newJs.setCountYh(js.getCountYh());

                //递归角色
                recursionJs(newJs, list);
                newList.add(newJs);
            }
        }
        return ResultBody.setData(newList);
    }

    /**
     * 查询分页数据
     *
     * @param jcqxJs
     * @param page
     * @param pageSize
     * @return
     */
    public JSONObject findListByPage(JcqxJs jcqxJs, long page, long pageSize) {

        Page<JcqxJs> pageObj = new Page<>(page, pageSize);
        IPage<JcqxJs> result = jcqxJsMapper.selectPage(pageObj, new QueryWrapper<JcqxJs>().setEntity(jcqxJs));

        return ResultBody.setData(result.getTotal(), result.getRecords());
    }


    /**
     * 新增
     *
     * @param jcqxJs
     * @return
     */
    public JSONObject add(JcqxJs jcqxJs) {
        jcqxJs.setCjsj(LocalDateTime.now());
        jcqxJs.setCjr(getYhid());
        jcqxJs.setBgsj(LocalDateTime.now());
        jcqxJs.setBgr(getYhid());
        return ResultBody.setData(jcqxJsMapper.insert(jcqxJs));
    }


    /**
     * 修改
     *
     * @param jcqxJs
     * @return
     */
    public JSONObject update(JcqxJs jcqxJs) {
        jcqxJs.setBgsj(LocalDateTime.now());
        jcqxJs.setBgr(getYhid());
        return ResultBody.setData(jcqxJsMapper.updateById(jcqxJs));
    }


    /**
     * 删除
     *
     * @param jcqxJs
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject delete(JcqxJs jcqxJs) {
        //删除角色下资源
        JcqxJszy jszy = new JcqxJszy();
        jszy.setJsid(jcqxJs.getJsid());
        jszyMapper.delete(new QueryWrapper<JcqxJszy>().setEntity(jszy));
        //删除角色下用户
        JcqxYhjs yhjs = new JcqxYhjs();
        yhjs.setJsid(jcqxJs.getJsid());
        yhjsMapper.delete(new QueryWrapper<JcqxYhjs>().setEntity(yhjs));

        return ResultBody.setData(jcqxJsMapper.delete(new QueryWrapper<JcqxJs>().setEntity(jcqxJs)));
    }

    @Override
    public JSONObject findCountZycdjs(JcqxJs jcqxJs) {
        Integer count = jcqxJsMapper.findCountZycdjs(jcqxJs);

        return ResultBody.setData(count);
    }

    @Override
    public JSONObject findYyzylistAll(JcqxJs jcqxJs) {
        List<JcqxGnzy> newList = new ArrayList<>();

        QueryWrapper<JcqxGnzy> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("pxh");
        List<JcqxGnzy> list = gnzyMapper.selectList(wrapper);
        for (JcqxGnzy gnzy : list) {
            if (gnzy.getFcdid() == null) {
                JcqxGnzy zy = new JcqxGnzy();
                BeanUtils.copyProperties(gnzy, zy);

                //递归资源
                recursionGnzy(zy, list);
                newList.add(zy);
            }
        }

        //获取角色下资源列表
        List<JcqxGnzy> jsxzy = jcqxJsMapper.findCkeckedYyzy(jcqxJs);

        JSONObject json = new JSONObject();
        json.put("gnzyList", newList);
        json.put("jszyList", jsxzy);

        return ResultBody.setData(json.toJSONString());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject updateJsxzy(String str) {
        Integer count = 0;

        JSONObject json = JSON.parseObject(str);
        JSONArray array = json.getJSONArray("gnzyid");
        String jsid = json.get("jsid").toString();
        JcqxJszy jszy = new JcqxJszy();
        jszy.setJsid(jsid);

        //先删除jsid下的所有资源后再添加
        jszyMapper.delete(new QueryWrapper<JcqxJszy>().setEntity(jszy));

        for (Object gnzyid : array) {
            JcqxJszy jcqxJszy = new JcqxJszy();
            jcqxJszy.setJsid(jsid);
            jcqxJszy.setGnzyid((String) gnzyid);
            jcqxJszy.setCjsj(LocalDateTime.now());
            jcqxJszy.setCjr(getYhid());
            jcqxJszy.setBgsj(LocalDateTime.now());
            jcqxJszy.setBgr(getYhid());

            jszyMapper.insert(jcqxJszy);
            count++;
        }

        return ResultBody.setData(count);
    }

    @Override
    public JSONObject findJsxyhlist(JsglQuery jsglQuery) {
        Page<JsglQuery> pageObj = new Page<>(jsglQuery.getPage(), jsglQuery.getPageSize());
        IPage<YhjsVO> result = jcqxJsMapper.findJsxyhlist(pageObj, jsglQuery);
        List<YhjsVO> list = result.getRecords();

        for (YhjsVO yhjsVO : list) {
            JcqxYhjsmx yhjsmx = new JcqxYhjsmx();
            yhjsmx.setJsid(yhjsVO.getJsid());
            yhjsmx.setYhid(yhjsVO.getYhid());
            List<YhjsmxVO> list1 = jcqxJsMapper.findYhjsmxList(yhjsmx);
            StringBuilder jsmx = new StringBuilder();
            for (YhjsmxVO vo : list1) {
                if (StringUtils.isNotBlank(vo.getBmmc())) {
                    jsmx.append(vo.getBmmc()).append("，");
                }
                if (StringUtils.isNotBlank(vo.getKzzd1())) {
                    jsmx.append(vo.getKzzd1()).append("，");
                }
                if (StringUtils.isNotBlank(vo.getKzzd2())) {
                    jsmx.append(vo.getKzzd2()).append("，");
                }
                if (StringUtils.isNotBlank(vo.getKzzd3())) {
                    jsmx.append(vo.getKzzd3()).append("，");
                }
                if (StringUtils.isNotBlank(vo.getKzzd4())) {
                    jsmx.append(vo.getKzzd4()).append("，");
                }
            }
            if (StringUtils.isNotBlank(jsmx.toString())) {
                yhjsVO.setJsmx(jsmx.toString());
            } else {
                yhjsVO.setJsmx("---");
            }

            List<JcqxBm> bmList = jcqxJsMapper.findBmList(yhjsVO.getYhid());
            int bm_num = bmList.size();
            StringBuilder bm = new StringBuilder();
            if (bm_num != 0) {
                for (int i = 0; i < bmList.size(); i++) {
                    String bmmc = bmList.get(i).getBmmc();
                    if (i == 0) {
                        bm.append(bmmc);
                        continue;
                    }
                    bm.append("，").append(bmmc);
                }
                yhjsVO.setBmmc(bm.toString());
            } else {
                yhjsVO.setBmmc("---");
            }
        }
        result.setRecords(list);

        return ResultBody.setData(result.getTotal(), result.getRecords());
    }

    @Override
    public JSONObject findYhList(JsglQuery jsglQuery) {
        Page<JsglQuery> pageObj = new Page<>(jsglQuery.getPage(), jsglQuery.getPageSize());
        IPage<YhglVO> result = jcqxJsMapper.findYhList(pageObj, jsglQuery);
        List<YhglVO> list = result.getRecords();

        for (YhglVO vo : list) {
            List<JcqxBm> bmList = jcqxJsMapper.findBmList(vo.getYhid());
            int bm_num = bmList.size();
            StringBuilder bm = new StringBuilder();
            if (bm_num != 0) {
                for (int i = 0; i < bmList.size(); i++) {
                    String bmmc = bmList.get(i).getBmmc();
                    if (i == 0) {
                        bm.append(bmmc);
                        continue;
                    }
                    bm.append("，").append(bmmc);
                }
                vo.setBmmc(bm.toString());
            } else {
                vo.setBmmc("---");
            }
        }
        result.setRecords(list);
        return ResultBody.setData(result.getTotal(), result.getRecords());
    }

    @Override
    public JSONObject addJsyh(JcqxYhjs yhjs) {
        int size = 0;
        //查找该角色及上层的所有的jsid
        List<String> list = jcqxJsMapper.findScjsid(yhjs.getJsid());
        for (String jsid : list) {
            String jsxyh = jcqxJsMapper.listJsyh(yhjs);
            if (jsxyh == null) {
                JcqxYhjs jcqxYhjs = new JcqxYhjs();
                jcqxYhjs.setJsid(jsid);
                jcqxYhjs.setYhid(yhjs.getYhid());
                jcqxYhjs.setCjsj(LocalDateTime.now());
                jcqxYhjs.setCjr(getYhid());
                jcqxYhjs.setBgsj(LocalDateTime.now());
                jcqxYhjs.setBgr(getYhid());
                yhjsMapper.insert(jcqxYhjs);
                size++;
            }
        }
        return ResultBody.setData(size);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject delJsyh(JcqxYhjs yhjs) {
        int i = yhjsMapper.delete(new QueryWrapper<JcqxYhjs>().setEntity(yhjs));
        JcqxYhjsmx yhjsmx = new JcqxYhjsmx();
        yhjsmx.setYhid(yhjs.getYhid());
        yhjsmx.setJsid(yhjs.getJsid());
        int j = yhjsmxMapper.delete(new QueryWrapper<JcqxYhjsmx>().setEntity(yhjsmx));
        return ResultBody.setData(i + j);
    }

    @Override
    public JSONObject findYhjsmxList(JsglQuery jsglQuery) {
        Page<JsglQuery> pageObj = new Page<>(jsglQuery.getPage(), jsglQuery.getPageSize());
        IPage<YhjsmxVO> result = jcqxJsMapper.getYhjsmxlist(pageObj, jsglQuery);
        return ResultBody.setData(result.getTotal(), result.getRecords());
    }

    @Override
    public JSONObject findBmlist() {
        List<JcqxBm> bmList = bmMapper.selectList(new QueryWrapper<JcqxBm>().orderByAsc("pxh"));
        return ResultBody.setData(bmList);
    }

    @Override
    public JSONObject findYhbmCount(JsglQuery jsglQuery) {
        Integer count = jcqxJsMapper.findYhbmCount(jsglQuery);
        return ResultBody.setData(count);
    }

    @Override
    public JSONObject addYhjsmx(JcqxYhjsmx yhjsmx) {
        yhjsmx.setCjsj(LocalDateTime.now());
        yhjsmx.setCjr(getYhid());
        yhjsmx.setBgsj(LocalDateTime.now());
        yhjsmx.setBgr(getYhid());
        return ResultBody.setData(yhjsmxMapper.insert(yhjsmx));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject deleteYhjsmx(JcqxYhjsmx yhjsmx) {
        //第一步，删除用户角色明细
        int i = yhjsmxMapper.deleteById(yhjsmx.getId());

        //第二步，通过用户角色明细删除用户角色
        Integer j = jcqxJsMapper.deleteYhjsByYhjsmx(yhjsmx);

        //第三步，通过用户角色明细删除用户部门
        Integer k = jcqxJsMapper.deleteYhbmByYhjsmx(yhjsmx);
        return ResultBody.setData(i + j + k);
    }

    @Override
    public JSONObject updateFjsid(JcqxJs jcqxJs) {
        jcqxJs.setBgsj(LocalDateTime.now());
        jcqxJs.setBgr(getYhid());
        return ResultBody.setData(jcqxJsMapper.updateById(jcqxJs));
    }

    //递归角色
    private JcqxJs recursionJs(JcqxJs newJs, List<JcqxJs> list) {
        boolean flag = false;
        List<JcqxJs> newList = new ArrayList<>();
        for (JcqxJs jcqxJs : list) {
            if (!StringUtils.isBlank(jcqxJs.getFjsid()) && jcqxJs.getFjsid().equals(newJs.getJsid())) {
                flag = true;
                JcqxJs js = new JcqxJs();
                js.setJsid(jcqxJs.getJsid());
                js.setJsmc(jcqxJs.getJsmc());
                js.setJslx(jcqxJs.getJslx());
                js.setFjsid(jcqxJs.getFjsid());
                js.setPxh(jcqxJs.getPxh());
                js.setCountZy(jcqxJs.getCountZy());
                js.setCountYh(jcqxJs.getCountYh());

                newList.add(recursionJs(js, list));
            }
        }
        if (flag) {
            newJs.setChildren(newList);
            return newJs;
        } else {
            return newJs;
        }
    }

    //递归资源
    private JcqxGnzy recursionGnzy(JcqxGnzy newZy, List<JcqxGnzy> list) {
        boolean flag = false;
        List<JcqxGnzy> newList = new ArrayList<>();
        for (JcqxGnzy gnzy : list) {
            if (!StringUtils.isBlank(gnzy.getFcdid()) && gnzy.getFcdid().equals(newZy.getGnzyid())) {
                flag = true;
                JcqxGnzy zy = new JcqxGnzy();
                BeanUtils.copyProperties(gnzy, zy);

                newList.add(recursionGnzy(zy, list));
            }
        }
        if (flag) {
            newZy.setChildren(newList);
            return newZy;
        } else {
            return newZy;
        }
    }
}
